﻿using UnityEngine;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Unity.Collections;
using Unity.Jobs;
using Unity.Rendering;
using Jinndev.ECS;

namespace Jinndev.Rendering2D {

    [UpdateAfter(typeof(CustomCullingSystem))]
    public class ZIndexSortingSystem : JobComponentSystem {

        public Camera camera;

        protected override JobHandle OnUpdate(JobHandle inputDeps) {
            if (camera == null) {
                return inputDeps;
            }
            inputDeps.Complete();

            Vector3 center = camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
            Vector3 topRight = camera.ViewportToWorldPoint(new Vector3(1, 1, 0));

            Vector2 halfScreen = topRight - center;

            inputDeps = Entities.WithNone<Culled>().ForEach((ref Translation translation, ref ZIndexSorting zIndexSorting) => {
                float3 pos = translation.Value;
                if (!zIndexSorting.initialized) {
                    zIndexSorting.baseZ = pos.z;
                    zIndexSorting.initialized = true;
                }
                // 使用z轴实现显示排序
                float deltaX = pos.x - center.x;
                float deltaY = pos.y - center.y;

                float deltaZ = math.round(deltaY / halfScreen.y * 100) * 0.01f + 0.01f * deltaX / halfScreen.x;

                pos.z = zIndexSorting.baseZ + deltaZ;
                translation.Value = pos;
            }).Schedule(inputDeps);
            inputDeps.Complete();

            return inputDeps;
        }

   

    }

}
